package com.yuandian.bpm.bi.modules.quartz.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuandian.bpm.bi.modules.customs.sevice.CustomReportService;
import com.yuandian.bpm.bi.modules.quartz.enums.TaskStateEnum;
import com.yuandian.bpm.bi.modules.quartz.enums.TaskTypeEnum;
import com.yuandian.bpm.bi.modules.quartz.mapper.ConfReportTaskInfoMapper;
import com.yuandian.bpm.bi.modules.quartz.service.HandelBaseService;
import com.yuandian.bpm.bi.modules.quartz.util.CollectHardwareUtils;
import com.yuandian.bpm.bi.modules.quartz.util.JobUtil;
import com.yuandian.bpm.bi.modules.quartz.vo.ConfReportRunningTaskVo;
import com.yuandian.bpm.bi.modules.quartz.vo.ConfReportTaskInfo;
import com.yuandian.bpm.bi.modules.quartz.vo.ConfReportTaskVo;
import com.yuandian.bpm.bi.modules.quartz.vo.QuartzBean;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 *  <p>
 *      心跳任务：
 * 			比较数据库任务表里面显示正在执行的任务与Quartz实际正在运行的任务进行比较，从而更新数据表状态
 * 	</p>
 *
 * @Author: LinShiHe
 * @Date: 2022/9/19 16:20
 */
@Slf4j
@Service("handelHeartbeatTaskServiceImpl")
public class HandelHeartbeatTaskServiceImpl implements HandelBaseService {

	@Autowired
	private ConfReportTaskInfoMapper confReportTaskInfoMapper;

	@Autowired
	CustomReportService customReportService;


	@Autowired
	private JobUtil jobUtils;

	private static JobUtil jobUtilsStatic;


	@PostConstruct
	public void init() {
		jobUtilsStatic = this.jobUtils;
	}

	@Override
	public ConfReportTaskVo handleData(ConfReportTaskInfo confReportTaskInfo, JobExecutionContext context) {
		log.info("[心跳任务]-开始执行。。。");
		long sTime = System.currentTimeMillis();
		List<Integer> taskIdList = new ArrayList<>();
		ConfReportTaskVo resultVo = new ConfReportTaskVo();                    // 结果集
		resultVo.setTaskType(TaskTypeEnum.SYSTEM_INTERNAL.toString());        // 任务类型： 系统类

		try {
			// 本机IP
			String taskExecuteIp = CollectHardwareUtils.getInet4Address();
			ConfReportTaskInfo param = new ConfReportTaskInfo();
			param.setTaskExecuteIp(taskExecuteIp);
			param.setTaskState(1);


			// 查询属于本机IP且表示正在执行的任务列表
			Page<ConfReportRunningTaskVo> page = confReportTaskInfoMapper.getRunningTaskList(new Page<>(1, -1), param);

			// 查询Quartz中正在执行的任务列表
			List<QuartzBean> allJobs = jobUtilsStatic.getAllJobs();
			List<String> extractedList = allJobs.stream()
					.map(QuartzBean::getJobName)
					.collect(Collectors.toList());

			// 判断与实际再Quartz中不符的任务,加入列表后续更新表数据状态
			if (page != null && page.getRecords() != null) {
				for (ConfReportRunningTaskVo taskVo : page.getRecords()) {
					if (!extractedList.contains(taskVo.getId().toString())) {
						taskIdList.add(taskVo.getId());
					}
				}

				if (taskIdList.size() > 0) {
					// 更新表数据状态
					confReportTaskInfoMapper.startOrStopTask(taskIdList, TaskStateEnum.SUSPEND.getCode());
				}
			}

			log.info("[心跳任务]-本次调度结束，调度时间：{}，更新任务数：{}, 任务ID：{}, 耗时：{} MS",
					context.getScheduledFireTime(),
					taskIdList.size(),
					taskIdList,
					System.currentTimeMillis() - sTime);

		} catch (Exception e) {
			e.printStackTrace();
			log.error("[心跳任务]-执行异常:{}", e.getMessage());
		}

		return resultVo;
	}

	@Override
	public void monitorThead(ConfReportTaskInfo confReportTaskInfo) {}

	@Override
	public void insertData(ConfReportTaskInfo confReportTaskInfo) throws Exception {}
}
